package com.speech.utils;

import android.media.MediaRecorder;
import android.os.Environment;
import android.text.format.DateFormat;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

public class AudioManager {

    private static AudioManager mInstance;

    private MediaRecorder mMediaRecorder;

    private boolean bPrerared = false;

    private AudioManager() {
    }

    public interface AudioStateListener {
        void wellPrepared();
    }

    public AudioStateListener mListener;

    public void setOnAudioStateListener(AudioStateListener listener) {
        mListener = listener;
    }

    public static AudioManager getInstance() {
        if (mInstance == null) {
            synchronized (AudioManager.class) {
                if (mInstance == null) {
                    mInstance = new AudioManager();
                }
            }
        }

        return mInstance;
    }

    String mDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test_sound_file/";
    private String fileName = null;

    public void prepareAudio() {
        try {
            File dir = new File(mDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            fileName = DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".mp4";
            File file = new File(dir, fileName);

            mMediaRecorder = new MediaRecorder();
            mMediaRecorder.setOutputFile(file.getAbsolutePath());
            Log.d("fzw", file.getAbsolutePath());

            /* ②setAudioSource/setVedioSource */
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风
            /*
             * ②设置输出文件的格式：THREE_GPP/MPEG-4/RAW_AMR/Default THREE_GPP(3gp格式
             * ，H263视频/ARM音频编码)、MPEG-4、RAW_AMR(只支持音频且音频编码要求为AMR_NB)
             */
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//mp4
            /* ②设置音频文件的编码：AAC/AMR_NB/AMR_MB/Default 声音的（波形）的采样 */
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);


            mMediaRecorder.prepare();

            mMediaRecorder.start();

            bPrerared = true;
            if (mListener != null) {
                mListener.wellPrepared();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    // 获取当前音量大小
    public int getVoiceLevel(int maxLevel) {
        if (bPrerared) {
            try {
                return maxLevel * mMediaRecorder.getMaxAmplitude() / 32768 + 1;
            } catch (Exception e) {
                //获取失败就不管了
            }
        }
        return 1;
    }

    public void release() {
        try {
            if (mMediaRecorder != null) {
                mMediaRecorder.setOnErrorListener(new MediaRecorder.OnErrorListener() {
                    @Override
                    public void onError(MediaRecorder mr, int what, int extra) {

                    }
                });
                mMediaRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {
                    @Override
                    public void onInfo(MediaRecorder mr, int what, int extra) {

                    }
                });
                mMediaRecorder.setPreviewDisplay(null);
            }
            mMediaRecorder.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
        } catch (RuntimeException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }

    }

    public void cancel() {
        String str = fileName;
        release();
        //TODO:再删掉录音文件，还没写
        File file = new File(mDir, str);
        if (file.exists()) {
            file.delete();
        }
    }

}
